import validate from 'wechat-validate'
Page({
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
    redirectURL: ''
  },
  onLoad({
    redirectURL
  }) {
    this.setData({
      redirectURL
    })
  },
  behaviors: [validate],
  rules: {
    mobile: [{
        required: true,
        message: '请填写手机号码!'
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请检查手机号码是否正确!'
      },
    ],
    code: [{
        required: true,
        message: '请填写短信验证码!'
      },
      {
        pattern: /^\d{6}$/,
        message: '请检查短信验证码是否正确!'
      }
    ]

  },
  async getSMScode() {
    const {
      valid,
      message
    } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    this.setData({
      countDownVisible: true
    })
    const res = await wx.http.get('/code', {
      mobile: this.data.mobile
    })
    if (res.code !== 10000) return wx.utils.toast('获取验证码失败')
    wx.utils.toast(res.data.code)
  },
  countDownChange(ev) {
    const {
      valid,
      message
    } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 点击登录按钮

  async submint() {
    // 验证码 rules 中定义的全部数据
    const isAllValid = this.validate()
    if (!isAllValid) return
    const {
      code,
      data
    } = await wx.http.post("/login", {
      mobile: this.data.mobile,
      code: this.data.code
    })
    if (code !== 10000) return wx.utils.toast('登录失败')

    const app = getApp()
    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)
    wx.redirectTo({
      url: this.data.redirectURL,
    })
    wx.utils.toast('登录成功')
  }
})